package reflect;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

public class A {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//        Calc calc = new BImpl();
//        System.out.println(calc.add(1, 2));

//        Calc calc = new CImpl();
//        System.out.println(calc.add(1, 2));

        // 通过反射动态加载类，在配置文件中配置Calc的实现类
        // 1. 加载配置文件bean.properties
        ///InputStream inputStream = A.class.getResourceAsStream("/bean.properties");
        InputStream inputStream = A.class.getClassLoader().getResourceAsStream("bean.properties");

        // 2. 获得Calc的实现类的全路径名
        Properties properties = new Properties();
        properties.load(inputStream);
        String className = properties.getProperty("calc");
        System.out.println(className);

        // 3. 使用反射创建对象
        //Class<?> aClass = Class.forName(className);
        Class<? extends Calc> aClass = Class.forName(className).asSubclass(Calc.class);
        Calc calc = aClass.getDeclaredConstructor().newInstance();

        // 4. 调用对象的方法
        System.out.println(calc.add(1, 2));
    }
}
